package com.tadpole.music.presenter.wechat;


import com.tadpole.music.bean.WeChatUserInfoBean;
import com.tadpole.music.callback.BaseCallback;
import com.tadpole.music.config.UrlConfig;
import com.tadpole.music.iView.wechat.UserInfoWeChatIView;
import com.tadpole.music.model.base.DataModel;
import com.tadpole.music.model.base.ModelToken;
import com.tadpole.music.presenter.base.BasePresenter;
import com.tadpole.music.utils.JsonParseUtil;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 获取微信的用户信息
 * Created By 孙岩
 * on 2020/11/9
 */
public class UserInfoWeChatPresenter extends BasePresenter<UserInfoWeChatIView> {
    @SuppressWarnings("unchecked")
    public void getUserInfo(String openId, String access_token) {
        if (isViewAttached()) {
            String url = UrlConfig.geWeChatUserInfo + access_token + "&openId=" + openId;
            DataModel.request(ModelToken.GET_REQUEST)
                    .url(url)
                    .execute(new BaseCallback<String>() {
                        @Override
                        public void onSuccess(String data) {
                            try {
                                JSONObject obj = new JSONObject(data);
                                WeChatUserInfoBean bean = new WeChatUserInfoBean(
                                        JsonParseUtil.getStr(obj, "openid"),
                                        JsonParseUtil.getStr(obj, "nickname"),
                                        JsonParseUtil.getInt(obj, "sex"),
                                        JsonParseUtil.getStr(obj, "language"),
                                        JsonParseUtil.getStr(obj, "city"),
                                        JsonParseUtil.getStr(obj, "province"),
                                        JsonParseUtil.getStr(obj, "country"),
                                        JsonParseUtil.getStr(obj, "headimgurl"),
                                        JsonParseUtil.getStr(obj, "unionid")
                                );
                                getView().showUserInfo(bean);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onFailure(String msg) {

                        }

                        @Override
                        public void onComplete() {

                        }

                        @Override
                        public void onBefore() {

                        }
                    });
        }
    }
}
